package com.bdqn.t382.lx.filter;

import com.bdqn.t382.lx.pojo.SysUser;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

public class Filter implements jakarta.servlet.Filter {

    /* 初始化 */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化");
        jakarta.servlet.Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String requestURI = httpServletRequest.getRequestURI();
        if (requestURI.endsWith("/animals/login") || requestURI.endsWith("/animals/doLogin")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        SysUser user = (SysUser) httpServletRequest.getSession().getAttribute("user");
        if (user != null) {
            if (requestURI.endsWith("/animals/add") || requestURI.endsWith("/animals/formAdd") || requestURI.endsWith("/animals/delete") ||
                    requestURI.endsWith("/animals/view") || requestURI.endsWith("/animals/formUpdate")) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
            Long roleId = user.getRoleId();
            if (roleId == 1) {
                httpServletRequest
                        .getRequestDispatcher("/animals/page")
                        .forward(httpServletRequest, httpServletResponse);
            } else if (roleId == 2 || roleId == 3) {
                httpServletRequest
                        .getRequestDispatcher("/animals/list")
                        .forward(httpServletRequest, httpServletResponse);
            }
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            httpServletResponse.sendRedirect("/Animals/erro.jsp");
        }
    }

    /* 销毁 */
    @Override
    public void destroy() {
        System.out.println("销毁");
        jakarta.servlet.Filter.super.destroy();
    }
}